package com.PuzGame.combinenumbers.Activities;


import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.SystemClock;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.PuzGame.combinenumbers.ChallengerLevel;
import com.PuzGame.combinenumbers.Level.LevelStatus;
import com.PuzGame.combinenumbers.ChallengeeLevel;
import com.PuzGame.combinenumbers.R;
import com.PuzGame.combinenumbers.RateThisApp;
import com.PuzGame.combinenumbers.Tools;
import com.PuzGame.combinenumbers.ServerCommunication.GetAndPostItems.Get_UserData.UserData;
import com.PuzGame.combinenumbers.customViews.CountUp;
import com.PuzGame.combinenumbers.customViews.CustomPopupWindow;
import com.google.android.gms.ads.InterstitialAd;
import com.google.gson.Gson;

public class ChallengerActivity extends MainActivity{

	private Context context = this;
	private Date StartDateTime;
	private Intent resultIntent;
	private UserData userData;
	
	//private Chronometer mChronometer;
	private CountUp stopper;

	private void RestoreChallengeLevel(String jsonLevel)
	{
		
		ChallengerLevel RestoredLevel = null;
		
		
		RestoredLevel = (ChallengerLevel) ChallengerLevel.fromJson(jsonLevel, ChallengerLevel.class);
		
		if(RestoredLevel != null)
		{
			SetExistingLevel(RestoredLevel);
			
			if(lvl.getStatus() == LevelStatus.CREATED)
			{
				lvl.setStatus(LevelStatus.IN_PROGRESS);
			}

			StartDateTime = RestoredLevel.getDateOfCreation();
	
		}
	}
	
	

	public int GetLayoutId() {
		return R.layout.activity_challenger;
	}
	
	public void initSpecificsViews() {
		// Prepare the Interstitial Ad
		interstitial = new InterstitialAd(ChallengerActivity.this);
		stopper = (CountUp) findViewById(R.id.stopper);
		stopper.setVisibility(View.VISIBLE);
		resultIntent = new Intent();
		//resultIntent.putExtra("Time", -3);
	}

	
	public void OnstartSpecifics() {
		
		String jsonLevel = getIntent().getStringExtra("PreparedChallengeLevel");
		
		String jsonUserData = getIntent().getStringExtra("PreparedUserData");
		
		Gson gson = new Gson();
		userData = gson.fromJson(jsonUserData, UserData.class);
		
	    RestoreChallengeLevel(jsonLevel);
		
		if(StartDateTime!=null)
		{
			Date now = new Date();
			long diff = now.getTime() - StartDateTime.getTime();

			stopper.setBase(SystemClock.elapsedRealtime()-diff);
		}
		stopper.start();
	}
	
	
	public void SetExistingLevel(ChallengerLevel restoredLevel) {

		lvl = new ChallengerLevel(restoredLevel, this);

		GoalTV.setText(Long.toString(lvl.getGoal()));

		ImageViewMarkerRight.setBackgroundResource(GetRandomMarkerRightResource());
		ImageViewMarkerLeft.setBackgroundResource(GetRandomMarkerLeftResource());
		ImageViewMarkerCircle.setBackgroundResource(GetRandomMarkerCircleResource());

		SetLevelNoText();

	}

	public void SetLevelNoText() {
		LevelNoTV.setText(String.format(getString(R.string.levelNoChallenge), lvl.getStage(),"Name Here"));
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.challenge_arena, menu);

		this.menu = menu;

		MenuItem TempMenuItem = this.menu.findItem(R.id.menu_overflow);


		if(RateThisApp.AlreadyRated())
		{
			MenuItem RateMenuItem = TempMenuItem.getSubMenu().findItem(R.id.rate);
			RateMenuItem.setVisible(false);
		}
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.share_level) {

			shareIt();

			return true;
		}

		if (id == R.id.surrender || id == R.id.solution) {

			Surrender();

			return true;
		}	

		if (id == R.id.statistics) {

			initiateStatisticsPopupWindow();

			return true;
		}	

		if (id == R.id.rate) {

			RateThisApp.RateNow(this);

			return true;
		}	
		
		if (id == R.id.settings) {

			ShowSettings(generalSettings);

			return true;
		}



		return super.onOptionsItemSelected(item);
	}
	
	
	protected void addStatiscticView(LinearLayout statisticsLL) {
		
		if(userData == null)
			return;
		
		int SizeOfDividers = 15;
		LayoutParams tvlp = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);

		TextView tv1 = new TextView(context);
		tv1.setLayoutParams(tvlp);
		tv1.setTextSize(SizeOfDividers);
		tv1.setTypeface(null, Typeface.BOLD);	
		tv1.setText(String.format(getString(R.string.levelNo), userData.stage));
		statisticsLL.addView(tv1);
		
		tv1 = new TextView(context);
		tv1.setLayoutParams(tvlp);
		tv1.setTextSize(SizeOfDividers);
		tv1.setTypeface(null, Typeface.BOLD);	
		tv1.setText(String.format(getString(R.string.stat_score), userData.score));
		statisticsLL.addView(tv1);
		
		tv1 = new TextView(context);
		tv1.setLayoutParams(tvlp);
		tv1.setTextSize(SizeOfDividers);
		tv1.setTypeface(null, Typeface.BOLD);	
		tv1.setText(String.format(getString(R.string.stat_rank), userData.rank));
		statisticsLL.addView(tv1);

		tv1 = new TextView(context);
		tv1.setLayoutParams(tvlp);
		tv1.setTextSize(SizeOfDividers);
		tv1.setTypeface(null, Typeface.BOLD);	
		tv1.setText(String.format(getString(R.string.stat_challenges_won), userData.challengesWon));
		statisticsLL.addView(tv1);
		
		tv1 = new TextView(context);
		tv1.setLayoutParams(tvlp);
		tv1.setTextSize(SizeOfDividers);
		tv1.setTypeface(null, Typeface.BOLD);	
		tv1.setText(String.format(getString(R.string.stat_challenges_lost), userData.challengesLost));
		statisticsLL.addView(tv1);

		tv1 = new TextView(context);
		tv1.setLayoutParams(tvlp);
		tv1.setTextSize(SizeOfDividers);
		tv1.setTypeface(null, Typeface.BOLD);	
		tv1.setText(String.format(getString(R.string.stat_surrenderings), userData.surrenderedCount));
		statisticsLL.addView(tv1);
				
	}


	private void Surrender() {
		final String sol = lvl.getSolution();
		final long goal = lvl.getGoal();

		resultIntent.putExtra("completeLevelImage", lvl.ToJson());
		
		
		CustomPopupWindow cpw = new CustomPopupWindow(context);
		cpw.
		setTitle(getString(R.string.do_you_give_up)).
		setMessage(String.format(getString(R.string.surrender_message_challenge))).
		setPositiveButton(true, getString(R.string.i_surrender),0,  new OnClickListener() {
			@Override
			public void onClick(View v) {
				SeeSolutionDialog(sol, goal);
				lvl.setStatus(LevelStatus.DONE_GAVE_UP);
			}
		}).
		setNegativeButton(true, getString(R.string.no_way),0,  null).
		setCancelable(null).
		Show();
	}


	public void SeeSolutionDialog(final String sol, final long goal) {
		
		CustomPopupWindow cpw = new CustomPopupWindow(context);
		cpw.
		setTitle(getString(R.string.do_you_want_to_see_solution)).
		setMessage(String.format(getString(R.string.solution_message), Score/4, Score )).
		setPositiveButton(true, getString(R.string.yes_please), 0, new OnClickListener() {
			@Override
			public void onClick(View v) {
				StoreAdditionalPoints(-(Math.abs(Score/4)));
				initiateSolutionPopupWindow(sol,goal);	
			}
		}).
		setNegativeButton(true, getString(R.string.no_thanks), 0, new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				setResult(Activity.RESULT_OK, resultIntent);
				finish();
			}
		}).
		setCancelable(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				setResult(Activity.RESULT_OK, resultIntent);
				finish();
			}
		}).
		Show();
	}




	@Override
	public void StageCleared() {

		stopper.stop();
		((ChallengerLevel)lvl).setTimeinSec((int) ((SystemClock.elapsedRealtime() - stopper.getBase())/1000));
		lvl.setStatus(LevelStatus.DONE_CLEARED);
		
		long AdditionalPoints = (long) Math.pow(lvl.getStage(), 2);
		Score = StoreAdditionalPoints(AdditionalPoints);
		
		playSound(R.raw.stage_cleared);
		CustomPopupWindow cpw = new CustomPopupWindow(context);
		cpw.
		setTitle(getString(R.string.stage_cleared)).
		setMessage(String.format(getString(R.string.great_job_message_challenge), AdditionalPoints,lvl.getStage())).
		setPositiveButton(true, getString(R.string.ok), 0, new OnClickListener() {
			@Override
			public void onClick(View v) {
				
				//resultIntent.putExtra("Time", (SystemClock.elapsedRealtime() - stopper.getBase())/1000);
				resultIntent.putExtra("completeLevelImage", lvl.ToJson());
				
				setResult(Activity.RESULT_OK, resultIntent);
				finish();
			}
		}).
		setNeutral1Button(false, "",R.drawable.share, new OnClickListener() {
			@Override
			public void onClick(View v) {
				shareIt();
			}
		}).setNeutral2Button(false, "",R.drawable.solution, new OnClickListener() {
			@Override
			public void onClick(View v) {
				initiateSolutionPopupWindow(lvl.getSolution(),lvl.getGoal());
			}
		}).
		Show();
		
	}


	protected void OnSolutionCancel() {
		super.OnSolutionCancel();
		if(lvl.getStatus() != LevelStatus.DONE_CLEARED)
		{
			setResult(Activity.RESULT_OK, resultIntent);
			finish();
		}
	}


}
